package org.leo.dm.component.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbManager {

	private static Connection getOracleConnection(String ip, String port, String instance, String user, String password) {
		String url = "jdbc:oracle:thin:@" + ip + ":" + port + ":" + instance;
		Connection conn = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * JDBC方式获取mysql数据库连接 Created on 2016年1月4日 .
	 * 
	 * @author wangchd
	 * @param ip
	 * @param port
	 * @param dbName
	 * @param user
	 * @param password
	 * @return {描述}
	 */
	private static Connection getMysqlConnection(String ip, String port, String dbName, String user, String password) {
		String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?rewriteBatchedStatements=true&characterEncoding=UTF-8";
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static Connection getConection(DbBean dbBean) {
		Connection conn = null;
		if (dbBean != null && dbBean.getType() != null) {
			DbTypeEnum dbTypeEnum = dbBean.getType();
			switch (dbTypeEnum) {
			case MYSQL:
				conn = getMysqlConnection(dbBean.getIp(), dbBean.getPort(), dbBean.getInstance(), dbBean.getUser(), dbBean.getPassword());
				break;
			case ORACLE:
				conn = getOracleConnection(dbBean.getIp(), dbBean.getPort(), dbBean.getInstance(), dbBean.getUser(), dbBean.getPassword());
				break;
			default:
				break;
			}
		}

		return conn;
	}

	/**
	 * 
	 * Created on 2016年1月6日 .
	 * 
	 * @author xiao_h
	 * @param rs
	 * @param stat
	 * @param conn
	 *            关闭数据库连接
	 */
	public static void close(ResultSet rs, Statement stat, Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stat != null) {
				stat.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * Created on 2016年1月6日 .
	 * 
	 * @author xiao_h
	 * @param conn
	 *            回滚
	 */
	public static void rollback(Connection conn) {
		try {
			if (conn != null) {
				conn.rollback();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
